package dao

import (
	"gin-ranking/api/auth/entity"
	"gin-ranking/common/result"
	"gin-ranking/common/util"
	"gin-ranking/pkg/db"
	"time"
)

type UserSessionDao struct{}

// Save 用户token
func (UserSessionDao) Save(userId string) string {

	userSession := entity.UserSession{
		UserId:      userId,
		Token:       util.SimpleUUID(), // token
		ExpiresTime: util.HTime{Time: util.Offset(util.CurrentTime(), util.Month, 1)},
		CreateTime:  util.HTime{Time: time.Now()},
		UpdateTime:  util.HTime{Time: time.Now()},
	}
	err := db.DB.Create(&userSession).Error
	if err != nil {
		panic(result.FailMag(err.Error()))
	}
	return userSession.Token
}

// DeleteId 根据主键删除
func (UserSessionDao) DeleteId(userId string) {
	err := db.DB.Where("user_id = ?", userId).Delete(&entity.UserSession{}).Error
	if err != nil {
		panic(result.FailMag(err.Error()))
	}
}

// GetById 根据主键查询
func (UserSessionDao) GetById(userId string) (userSession entity.UserSession) {
	db.DB.Where("user_id = ?", userId).Find(&userSession)
	return userSession
}

// GetByToken 根据token查询
func (UserSessionDao) GetByToken(token string) (userSession entity.UserSession) {
	db.DB.Where("token = ?", token).Find(&userSession)
	return userSession
}

// UpdateById 根据主键更新
func (UserSessionDao) UpdateById(userSession entity.UserSession) {
	//err := dao.DB.Where("user_id = ?", userSession.UserId).Update(&userSession).Error
	//if err != nil {
	//	panic(result.FailMag(err.Error()))
	//}
}
